package su.jet.common.irc.protocol.request;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Map;
import java.util.Set;

import su.jet.common.irc.domain.Message;
import su.jet.common.irc.domain.User;
import su.jet.common.irc.protocol.Session;
import su.jet.irc.server.service.DataService;

@SuppressWarnings("serial")
//[ek] TODO rename without owls omitted
public class SendMessageRequest implements Request {
	
	// [DF] XXX: This looks really strange? Is it not enough to have boolean constants?

	private Message message;
	
	//[DF] XXX: public? 
	private boolean isPublicMessage;
	
	public SendMessageRequest(Message message, boolean isPublicMessage) {
		this.message = message;
		this.isPublicMessage = isPublicMessage;
	}

	public Message getMessage() {
		return message;
	}

	public boolean isPublicMessage() {
		return isPublicMessage;
	}

	@Override
	public void process(Session session, Set<User> regUsers,
			Map<User, Session> onlineUsers, DataService dataService) throws IOException {
		
		Message message = this.getMessage();
		
		if (this.isPublicMessage())
			sendMessageToAll(message, onlineUsers);
		else
			sendMessage(session, message, onlineUsers);
		
		dataService.addMessageToHistory(message, new Timestamp(System.currentTimeMillis()));
	}
	
	private void sendMessage(Session session, Message message, 
			Map<User, Session> onlineUsers) throws IOException {
		
		Session newProtocol = null;
		User receiver = message.getReceiver();
		
		for (User user : onlineUsers.keySet()){
			if (user.getNickName().equals(receiver.getNickName()))
					newProtocol = onlineUsers.get(user);
		}
		
		if (newProtocol != null) {
			
			newProtocol.sendMessage(message);
			
			message.setIsDelivered();
		}
		session.sendMessage(message);
	}
	
	private void sendMessageToAll(Message message, 
			Map<User, Session> onlineUsers) throws IOException {
		
		for (Session session : onlineUsers.values()) {
			session.sendMessage(message);
		}
	}
}